<!--  线 + 柱混合图 -->
<template>
  <div :id="id" style="height: 100%"></div>
</template>

<script setup lang="ts">
import * as echarts from "echarts";

const props = defineProps({
  id: String,
  data: Array<any>,
});

const options = {
  grid: {
    left: "1%",
    right: "1%",
    bottom: "1%",
    top: "2%",
    containLabel: true,
  },
  xAxis: {
    type: "value",
    axisLabel: {
      interval:0,
      rotate:40
    },
  },
  yAxis: {
    type: "category",
    data: [],
  },
  series: [
    {
      data: [],
      type: "bar",
      showBackground: true,
      backgroundStyle: {
        color: "rgba(50, 190, 189, 0.2)",
      },
    },
  ],
};

const chart = ref<any>("");
onMounted(() => {
  // 图表初始化
  chart.value = markRaw(
    echarts.init(document.getElementById(props.id) as HTMLDivElement)
  );
  chart.value.setOption(options);
  // 大小自适应
  window.addEventListener("resize", () => {
    chart.value.resize();
  });
});

onActivated(() => {
  if (chart.value) {
    chart.value.resize();
  }
});

watchEffect(() => {
  const { data } = props;
  if (Array.isArray(data) && chart.value) {
    const keys = data.map((item) => item.attrVal);
    const values = data.map((item) => item.length);
    options.yAxis.data = keys;
    options.series[0].data = values;
    chart.value.setOption(options);
  }
});
</script>
<style lang="scss" scoped>
.title {
  display: flex;
  justify-content: space-between;

  .download {
    cursor: pointer;

    &:hover {
      color: #32bebd;
    }
  }
}
</style>
